package au.edu.unsw.infs3634.gamifiedlearning;

import android.annotation.SuppressLint;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;

import androidx.appcompat.app.AppCompatActivity;

import com.google.android.material.dialog.MaterialAlertDialogBuilder;

import org.litepal.LitePal;

import java.util.Collections;
import java.util.List;

import au.edu.unsw.infs3634.gamifiedlearning.model.QuizModel;
import au.edu.unsw.infs3634.gamifiedlearning.model.Score;
import au.edu.unsw.infs3634.gamifiedlearning.model.UserModel;
import au.edu.unsw.infs3634.gamifiedlearning.utils.SPUtil;

public class Quiz_question extends AppCompatActivity {
    String continentName;
    public static String continent;
    private RadioGroup radioGroup;
    private List<QuizModel.Question> questionList;
    private TextView tvQuestion;
    private RadioButton rBtnA, rBtnB, rBtnC, rBtnD;

    private int id;
    private QuizModel.Question currentQuestion;
    private int currentIndex = 0;
    private UserModel userModel;
    private int userId;
    private List<Score> scoreList;
    private Score score;
    private TextView tvRight;
    private Button btnNext;
    private TextView tvNumber;
    private TextView tvTotal;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_quiz_question);
        initView();
        initData();
    }

    private void initView() {
        assert getSupportActionBar() != null;
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        tvRight = findViewById(R.id.tv_right);
        btnNext = findViewById(R.id.btn_next);
        radioGroup = findViewById(R.id.radioGroup);
        tvQuestion = findViewById(R.id.tvQuestion);
        rBtnA = findViewById(R.id.rBtnA);
        rBtnB = findViewById(R.id.rBtnB);
        rBtnC = findViewById(R.id.rBtnC);
        rBtnD = findViewById(R.id.rBtnD);
        tvNumber = (TextView) findViewById(R.id.tvNumber);
        tvTotal = (TextView) findViewById(R.id.tvTotal);

        radioGroup.setOnCheckedChangeListener(onCheckedChangeListener);
        btnNext.setOnClickListener(v -> {
            if (!isLastQuestion()) {
                updateQuestion();
                return;
            }
            userModel.save();
            //这里再查一次scoreList
            scoreList = LitePal.where("userId = ?", String.valueOf(userId)).find(Score.class);
            if (scoreList.size() == 6) {
                showRankDialog();
            } else {
                finish();
            }
        });
    }

    private RadioGroup.OnCheckedChangeListener onCheckedChangeListener = new RadioGroup.OnCheckedChangeListener() {
        @SuppressLint("NonConstantResourceId")
        @Override
        public void onCheckedChanged(RadioGroup group, int checkedId) {
            radioGroup.setOnCheckedChangeListener(null);
            switch (checkedId) {
                case R.id.rBtnA:
                    answer("A");
                    if (!"A".equals(currentQuestion.getRightTag())){
                        rBtnA.setBackgroundResource(R.drawable.shape_bg_red);
                        rBtnA.getBackground().setAlpha(50);
                    }
                    break;
                case R.id.rBtnB:
                    answer("B");
                    if (!"B".equals(currentQuestion.getRightTag())){
                        rBtnB.setBackgroundResource(R.drawable.shape_bg_red);
                        rBtnB.getBackground().setAlpha(50);
                    }
                    break;
                case R.id.rBtnC:
                    answer("C");
                    if (!"C".equals(currentQuestion.getRightTag())){
                        rBtnC.setBackgroundResource(R.drawable.shape_bg_red);
                        rBtnC.getBackground().setAlpha(50);
                    }
                    break;
                case R.id.rBtnD:
                    answer("D");
                    if (!"D".equals(currentQuestion.getRightTag())){
                        rBtnD.setBackgroundResource(R.drawable.shape_bg_red);
                        rBtnD.getBackground().setAlpha(50);
                    }
                    break;
            }
        }
    };

    @SuppressLint("SetTextI18n")
    private void initData() {
        userId = SPUtil.getInt(this, "userId", -1);
        userModel = LitePal.find(UserModel.class, userId);

        //intent & set title
        Intent intent = getIntent();
        continentName = intent.getStringExtra(continent);
        id = intent.getIntExtra("id", -1);
        setTitle(continentName);

        scoreList = LitePal.where("userId = ?", String.valueOf(userId)).find(Score.class);
        if (scoreList == null || scoreList.size() == 0) {
            score = new Score();
            score.setUserId(userId);
            score.setQuestionId(id);
            score.setName(continentName);
            score.save();
        } else {
            for (Score _score : scoreList) {
                if (_score.getQuestionId() == id) {
                    score = _score;
                    score.setScore(0);
                    score.save();
                }
            }
            if (score == null) {
                score = new Score();
                score.setQuestionId(id);
                score.setUserId(userId);
                score.setName(continentName);
                score.save();
            }
        }

        questionList = intent.getParcelableArrayListExtra("questionList");

        tvTotal.setText("/" + questionList.size());
        updateQuestion();
    }

    @SuppressLint("SetTextI18n")
    private void updateQuestion() {
        tvRight.setVisibility(View.INVISIBLE);
        btnNext.setVisibility(View.INVISIBLE);
        //clearCheck会触发onChecked，与期望不符，因此先移除监听事件，clearCheck之后再重新设置
       // radioGroup.setOnCheckedChangeListener(null);
        radioGroup.clearCheck();
        radioGroup.setOnCheckedChangeListener(onCheckedChangeListener);
        currentQuestion = questionList.get(currentIndex);
        tvQuestion.setText(currentQuestion.getTitle());
        List<QuizModel.Question.Option> optionList = currentQuestion.getOptionList();
        rBtnA.setText("A、"+optionList.get(0).getValue());
        rBtnB.setText("B、"+optionList.get(1).getValue());
        rBtnC.setText("C、"+optionList.get(2).getValue());
        rBtnD.setText("D、"+optionList.get(3).getValue());
        currentIndex++;


        //去除上一题选择的背景色恢复为未选择状态
        rBtnA.setBackgroundResource(R.drawable.shape_rb_whit);
        rBtnB.setBackgroundResource(R.drawable.shape_rb_whit);
        rBtnC.setBackgroundResource(R.drawable.shape_rb_whit);
        rBtnD.setBackgroundResource(R.drawable.shape_rb_whit);

        tvNumber.setText(String.valueOf(currentIndex));
    }

    private boolean isLastQuestion() {
        return currentIndex == questionList.size();
    }

    @SuppressLint("SetTextI18n")
    private void answer(String answer) {

        tvRight.setVisibility(View.VISIBLE);
        tvRight.setText("正确答案：" + currentQuestion.getRightTag());
        btnNext.setVisibility(View.VISIBLE);
        switch (currentQuestion.getRightTag()) {
            case "A":
                rBtnA.setBackgroundResource(R.drawable.shape_bg_green);
                rBtnA.getBackground().setAlpha(50);
                break;

            case "B":
                rBtnB.setBackgroundResource(R.drawable.shape_bg_green);
                rBtnB.getBackground().setAlpha(50);
                break;

            case "C":
                rBtnC.setBackgroundResource(R.drawable.shape_bg_green);
                rBtnC.getBackground().setAlpha(50);
                break;

            case "D":
                rBtnD.setBackgroundResource(R.drawable.shape_bg_green);
                rBtnD.getBackground().setAlpha(50);
                break;
        }
        if (currentQuestion.getRightTag().equals(answer)) {
            score.setScore(score.getScore() + 1);
            score.save();
        }
    }

    private void showRankDialog() {
        new MaterialAlertDialogBuilder(this).setTitle("当前排名").setMessage(getScoreInfo()).setNegativeButton("取消", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                finish();
            }
        }).setPositiveButton("确定", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                finish();
            }
        }).show();
    }

    private String getScoreInfo() {
        Collections.sort(scoreList);
        StringBuilder sb = new StringBuilder();

        for (int i = 0; i < scoreList.size(); i++) {
            Score score = scoreList.get(i);
            sb.append("第" + (i + 1) + "名 :").append(score.getName()).append(" ").append(score.getScore()).append("分").append("\n");
        }
        return sb.toString();
    }

    @Override
    public boolean onSupportNavigateUp() {
        finish();
        return true;
    }
}
